package com.squirrels.server.config;

import com.squirrels.server.router.ServerRouter;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * 创建者: FlyingSquirrels
 * 创建时间: 2024/7/29 17:32
 * 描述: netty配置
 */
@Slf4j
@Configuration
public class NettyConfig {

    @Resource
    private ServerRouter serverRouter;

    private Bootstrap bootstrap;
    private NioEventLoopGroup bossGroup;
    private ChannelFuture channelFuture;
    // 监听端口
    @Value("${netty.port}")
    private Integer listenPort;

    // 配置netty
    @PostConstruct
    public void udpBootstrap() {
        bossGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(bossGroup)
                .channel(NioDatagramChannel.class)
                .handler(serverRouter)
                .option(ChannelOption.SO_BROADCAST, true);
    }

    // 启动
    public void run() throws InterruptedException {
        channelFuture = bootstrap.bind(listenPort).sync();
        System.out.println("★★★ Server started: "+listenPort+" . ★★★");
    }


    // 优雅关闭
    public void closeGroup(){
        bossGroup.shutdownGracefully();
        // 通道关闭后执行的操作
        channelFuture.channel().closeFuture().addListener(future -> {
        });
    }

}